<script setup lang="ts">
import { ElButton, ElDialog, ElForm, ElFormItem, ElInput, ElMessage, ElMessageBox, FormInstance, FormRules } from 'element-plus';
import Table from '@/components/table/index.vue';
import useManageUse from './useManageTask';
import TaskEditDialog from '@/components/TaskEditDialog.vue';
import { deleteTask, TaskItem } from '@/services/task';
import { taskOptions } from 'common/src/utils/special';
import { toLonLatString } from 'common/src/utils/lnglat';
import dayjs from 'dayjs';
import { getTimestampFromCustomFormatZ } from 'common/src/utils/time';

const {
  list,
  getList,
  loading,
  total,
  page: pageNo,
  size: pageSize,
} = useManageUse();

const editVisible = ref(false);
const taskEditDialogRef = ref<InstanceType<typeof TaskEditDialog> | null>(null);

const handleDeleteRow = async (row: TaskItem) => {
  await ElMessageBox.confirm(
    `确定删除任务编号为“${row.name}”的任务吗？`,
    '删除任务',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'info',
      closeOnClickModal: false,
      closeOnPressEscape: false
    }
  );
  try {
    await deleteTask({ ids: String(row.id) });
    ElMessage({
      type: 'success',
      message: '操作成功',
    });
    handleQuery(1);
  } catch {
    ElMessage({
      type: 'warning',
      message: '操作失败，请重试',
    });
  }
};

const showEditDialog = (row: TaskItem) => {
  taskEditDialogRef.value?.editTask(row);
};

const showAddDialog = () => {
  taskEditDialogRef.value?.editTask();
};

const columns = [
  {
    prop: 'name',
    label: '任务编号',
    align: 'center',
  },
  {
    prop: 'name',
    label: '起终点',
    align: 'center',
    width: 400,
    render: (columnsProps: { row: TaskItem }) => {
      const { points } = columnsProps.row;
      const depPoint = points?.[0];
      const desPoint = points?.[points.length - 1];
      if (!depPoint || !desPoint) {
        return h('div', null, '--');
      }
      const dep = depPoint?.id ? depPoint.name! : toLonLatString(depPoint.longitude, depPoint.latitude);
      const des = desPoint?.id ? desPoint.name! : toLonLatString(desPoint.longitude, desPoint.latitude);
      return h('div', null, [
        h('div', null, dep),
        h('div', null, des),
      ]);
    },
  },
  {
    prop: 'ptdUtc',
    label: '出航时间',
    align: 'center',
    width: 240,
    render: (columnsProps: { row: TaskItem }) => {
      const { ptdUtc } = columnsProps.row;
      return h('span', null, dayjs(getTimestampFromCustomFormatZ(ptdUtc, 'YYYY/MM/DD HH:mm:ss')).format('YYYY/MM/DD HH:mm:ss') || '--');
    },
  },
  {
    label: '任务类型',
    align: 'center',
    width: 150,
    render: (columnsProps: { row: TaskItem }) => {
      const { taskStage } = columnsProps.row;
      const task = taskOptions.find(opt => opt.value === taskStage);
      return h('span', null, task?.label || '--');
    },
  },
  // {
  //   prop: 'created_time',
  //   label: '创建时间',
  //   align: 'center',
  //   width: 140,
  //   // render: (columnsProps: { row: TaskItem }) => {
  //   //   const { ptdUtc } = columnsProps.row;
  //   //   return h('span', null, dayjs(getTimestampFromCustomFormatZ(ptdUtc, 'YYYY/MM/DD HH:mm:ss')).format('YYYY/MM/DD HH:mm:ss') || '--');
  //   // },
  // },
  {
    label: '操作',
    align: 'center',
    width: 120,
    // fixed: 'right',
    renderBtns: [
      // { text: '编辑', onClick: (_idx: number, row: any) => showEditDialog(row), type: 'primary', link: true },
      { text: '删除', onClick: (_idx: number, row: any) => handleDeleteRow(row), type: 'danger', link: true },
    ]
  }
];

const handleQuery = (page: number, length: number = pageSize.value) => {
  getList({ page, length });
};

onMounted(() => {
  handleQuery(1);
});
</script>

<template>
  <div class="config-page">
    <div class="page-title">
      <span class="page-title-active">&nbsp;</span>
    </div>
    <div class="page-query" v-if="false">
      <ElForm :inline="true">
        <ElFormItem>
          <ElButton type="primary" @click="() => showAddDialog()">+ 创建任务</ElButton>
        </ElFormItem>
      </ElForm>
    </div>
    <div class="page-table-container">
      <Table
        :loading="loading"
        :list="list"
        height="calc(100vh - 35px - 62px - 50px - 40px - 60px)"
        :columns="columns"
        :total="total"
        :page-no="pageNo"
        :page-size="pageSize"
        :get-list="(pageNo: number, pageSize: number) => handleQuery(pageNo, pageSize)"
      />
    </div>
    <TaskEditDialog
      ref="taskEditDialogRef"
      v-model:visible="editVisible"
      show-mask
      center
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      @update="() => handleQuery(1)"
    />
  </div>
</template>

<style lang="less" scoped>
.home-container {
  height: calc(100vh - 35px);
}
</style>
